import { Tabs, Form, Button, Input } from "antd";
import CommonPage from "@/components/page/CommonPage";
import styled from "styled-components";
import UploadOne from "@/components/upload/UploadOne";
import { useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import { updateCurrent, updateCurrentPassword } from "@/api/user";
import useMyContext from "@/hooks/useContext";
import action from "@/store/action";
import { toLogin } from "@/utils/auth";
import { useLocation, useNavigate } from "react-router-dom";

const Styled = styled.div``;
const Profile = () => {
  const location = useLocation();
  const navigate = useNavigate();
  const dispath = useDispatch();
  const { messageApi } = useMyContext();
  const { userInfo } = useSelector((state) => state.user);

  const [infoFormRef] = Form.useForm();
  const [infoForm, setInfoForm] = useState({
    avatar: userInfo.data?.avatar || "",
    nickname: userInfo.data?.nickname || "",
    intro: userInfo.data?.intro || "",
    website: userInfo.data?.website || "",
  });

  const [passwordFormRef] = Form.useForm();
  const [passowrdForm, setPasswordForm] = useState({
    old_password: "",
    new_password: "",
    confirm_password: "",
  });

  const onTabChange = (key) => {
    console.log(key);
  };
  function UpdateFormModel(nVal) {
    setInfoForm({ ...infoForm, avatar: nVal.img });
  }
  async function updateProfile() {
    try {
      await infoFormRef.validateFields();
      const val = infoForm;
      await updateCurrent(val);
      messageApi.success("更新成功");
      await dispath(action.user.setUserInfo(val));
    } catch (error) {
      messageApi.error("更新失败");
    }
  }

  async function updatePassword() {
    try {
      await passwordFormRef.validateFields();
      const val = passowrdForm;
      const { code } = await updateCurrentPassword(val);
      if (code === 0) {
        messageApi.success("密码修改成功，请重新登陆");
        await dispath(action.user.logout());
        dispath(action.tags.resetTags());
        dispath(action.permission.resetPermission());
        toLogin(location, navigate);
      } else {
        messageApi.error("更新失败");
      }
    } catch (error) {
      messageApi.error("更新失败");
    }
  }

  const items = [
    {
      key: "website",
      label: "修改信息",
      children: (
        <div style={{ padding: "30px", display: "flex", alignItems: "center" }}>
          <div style={{ marginRight: "30px", width: "200px" }}>
            <UploadOne
              width={130}
              preview={infoForm.avatar}
              UpdateFormModel={UpdateFormModel}
            />
          </div>
          <Form
            name="update-wesite"
            style={{ flex: 0.3 }}
            form={infoFormRef}
            labelCol={{ span: 4 }}
            wrapperCol={{ span: 19 }}
            initialValues={{
              ...infoForm,
            }}
          >
            <Form.Item
              label="昵称"
              name="nickname"
              rules={[{ required: true, message: "请输入昵称" }]}
            >
              <Input
                placeholder="请输入昵称"
                value={infoForm.nickname}
                onChange={(e) => {
                  setInfoForm({
                    ...infoForm,
                    nickname: e.target.value,
                  });
                }}
              />
            </Form.Item>
            <Form.Item label="个人简介" name="intro">
              <Input
                placeholder="请输入个人简介"
                value={infoForm.intro}
                onChange={(e) => {
                  setInfoForm({
                    ...infoForm,
                    intro: e.target.value,
                  });
                }}
              />
            </Form.Item>
            <Form.Item label="个人网站" name="website">
              <Input
                placeholder="请输入个人网站"
                value={infoForm.website}
                onChange={(e) => {
                  setInfoForm({
                    ...infoForm,
                    website: e.target.value,
                  });
                }}
              />
            </Form.Item>
            <Form.Item>
              <Button type="primary" onClick={updateProfile}>
                修改
              </Button>
            </Form.Item>
          </Form>
        </div>
      ),
    },
    {
      key: "contact",
      label: "修改密码",
      children: (
        <div style={{ padding: "30px" }}>
          <Form
            name="update-pasword"
            form={passwordFormRef}
            labelCol={{ span: 1 }}
            wrapperCol={{ span: 3 }}
            initialValues={{ ...passowrdForm }}
          >
            <Form.Item
              label="旧密码"
              name="old_password"
              rules={[{ required: true, message: "请输入旧密码" }]}
              validateTrigger={["onBlur", "onChange"]}
            >
              <Input.Password
                placeholder="请输入旧密码"
                value={passowrdForm.old_password}
                onChange={(e) => {
                  setPasswordForm({
                    ...passowrdForm,
                    old_password: e.target.value,
                  });
                }}
              />
            </Form.Item>
            <Form.Item
              label="新密码"
              name="new_password"
              rules={[
                {
                  required: true,
                  message: !passowrdForm.old_password
                    ? "请输入旧密码"
                    : "请输入新密码",
                },
              ]}
              validateTrigger={["onBlur", "onChange"]}
            >
              <Input.Password
                placeholder="请输入新密码"
                value={passowrdForm.new_password}
                disabled={!passowrdForm.old_password}
                onChange={(e) => {
                  setPasswordForm({
                    ...passowrdForm,
                    new_password: e.target.value,
                  });
                }}
              />
            </Form.Item>
            <Form.Item
              label="确认密码"
              name="confirm_password"
              rules={[
                {
                  required: true,
                  message: !passowrdForm.new_password
                    ? "请输入新密码"
                    : "请再次输入新密码",
                },
              ]}
              validateTrigger={["onBlur", "onChange"]}
            >
              <Input.Password
                placeholder="请再次输入新密码"
                value={passowrdForm.confirm_password}
                disabled={!passowrdForm.new_password}
                onChange={(e) => {
                  setPasswordForm({
                    ...passowrdForm,
                    confirm_password: e.target.value,
                  });
                }}
              />
            </Form.Item>
            <Form.Item>
              <Button type="primary" onClick={updatePassword}>
                修改
              </Button>
            </Form.Item>
          </Form>
        </div>
      ),
    },
  ];
  return (
    <Styled>
      <CommonPage showHeader={false}>
        <Tabs items={items} onChange={onTabChange} />
      </CommonPage>
    </Styled>
  );
};

export default Profile;
